package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.BO.SearchQryCmd;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.ServiceUrlConst;
import com.authine.cloudpivot.ext.dto.BatchSubmitDto;
import com.authine.cloudpivot.ext.dto.FlowQueryDto;
import com.authine.cloudpivot.ext.enums.WorkFlowCodeEnum;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.DateUtils;
import com.authine.cloudpivot.ext.utils.HttpClients;
import com.authine.hermes.app.flow.runtime.dto.clientobject.HandleWorkItemValidMessageVO;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName FlowManageService
 * @Description: 流程管理
 * @Author bwh
 * @Date 2021/10/25
 * @Version V1.0
 **/
@Path("FlowManageService")
@Slf4j
public class FlowManageService extends ApplicationService {
    private final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 流程管理列表
     *
     * @param flowQueryDto 流程列表查询参数
     * @return 响应结果
     */
    @Path("searchFlowManageList")
    @POST
    @Operation(summary = "搜索流程管理任务列表", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> searchFlowManageList(@Parameter FlowQueryDto flowQueryDto) {
        log.info("查询待办数据：todoType:{}", flowQueryDto.getTodoType());
        SearchQryCmd cmd = new SearchQryCmd();
        cmd.setAppCode(StringUtils.isNotBlank(flowQueryDto.getAppCode()) ? flowQueryDto.getAppCode() : "");
        cmd.setModuleCode(StringUtils.isNotBlank(flowQueryDto.getModuleCode()) ? flowQueryDto.getModuleCode() : "");
        if (flowQueryDto.getTodoType() != 5) {
            cmd.setOriginatorList(Optional.ofNullable(flowQueryDto.getOriginator().stream().map(e -> e.getId()).collect(Collectors.toList())).orElse(new ArrayList<>()));
        }
        cmd.setInstanceName(StringUtils.isNotBlank(flowQueryDto.getInstanceName()) ? flowQueryDto.getInstanceName() : "");
        cmd.setType(flowQueryDto.getTodoType());
        cmd.setBizObjectId(StringUtils.isNotBlank(flowQueryDto.getBizObjectId()) ? flowQueryDto.getBizObjectId() : "");
        cmd.setInstanceState(StringUtils.isNotBlank(flowQueryDto.getInstanceState()) ? flowQueryDto.getInstanceState() : "");
        cmd.setWorkflowCode(StringUtils.isNotBlank(flowQueryDto.getWorkflowCode()) ? WorkFlowCodeEnum.getText(flowQueryDto.getWorkflowCode()) : "");
        if (StringUtils.isNotEmpty(flowQueryDto.getStartTime())) {
            cmd.setStartTime(DateUtils.formatDate(flowQueryDto.getStartTime(), DateUtils.parsePatterns[1]));
        }
        if (StringUtils.isNotEmpty(flowQueryDto.getEndTime())) {
            cmd.setEndTime(DateUtils.formatDate(flowQueryDto.getEndTime(), DateUtils.parsePatterns[1]));
        }
//        if(StringUtils.isEmpty(RequestContext.getCorpLoginId())) {
//            log.info("userId = {}", flowQueryDto.ge);
//            cmd.setUserId(userId);
//        }
        cmd.setUserId(RequestContext.getCorpLoginId());
        cmd.setPageNum(flowQueryDto.getPage() == null ? 0 : flowQueryDto.getPage());
        cmd.setPageSize(flowQueryDto.getSize() == null ? 20 : flowQueryDto.getSize());
        return search(cmd);
    }

    public SingleResponse<BOList> search(SearchQryCmd cmd) {
        SingleResponse<BOList> todoBOMultiResponse = new SingleResponse<>();
        String appCode = cmd.getAppCode();
//        String originator = cmd.getOriginator();
        List<String> originatorList = cmd.getOriginatorList();
        String instanceName = cmd.getInstanceName();
        // participant：当前流程处理人 instanceState：当前流程状态
        String participant = cmd.getParticipant();
        String instanceState = cmd.getInstanceState();
        String workflowCode = cmd.getWorkflowCode();
        String bizObjectId = cmd.getBizObjectId();
        Integer todoType = cmd.getType();
        Date startTime = cmd.getStartTime();
        Date endTime = cmd.getEndTime();
        String loginId = RequestContext.getCorpLoginId();
        log.info("查询任务, 当前用户. loginId = {}", loginId);
        log.info("userId = {}", cmd.getUserId());
        log.info("workflowCode = {}, originatorList = {}, instanceName = {}, startTime = {}, endTime = {}", workflowCode, JSON.toJSONString(originatorList), instanceName, startTime, endTime);
        if (StringUtils.isEmpty(loginId) && StringUtils.isNotBlank(cmd.getUserId())) {
            loginId = cmd.getUserId();
        }
        //本地调试的时候需要注释掉
        if (StringUtils.isBlank(loginId)) {
            //测试代码
//            loginId = "4028829b77beeece0177c86d33440002";
            return todoBOMultiResponse;
        }

        int pageNum = cmd.getPageNum();
        int pageSize = cmd.getPageSize();
        todoBOMultiResponse = searchByWorkflowNameOrModuleCodeOrOriginator(appCode, todoType, instanceName, instanceState, participant,
                originatorList, loginId, startTime, endTime, pageNum, pageSize, bizObjectId, workflowCode);
        //组装数据
//        List<TodoDto> todoDtos = assignmentTodoDto(todoBOMultiResponse.getData());
        return todoBOMultiResponse;
    }

    public SingleResponse<BOList> searchByWorkflowNameOrModuleCodeOrOriginator(String appCode, Integer todoType, String instanceName, String instanceState, String participant,
                                                                               List<String> originatorList, String loginId,
                                                                               Date startTime, Date endTime, int pageNum, int pageSize, String bizObjectId, String workflowCode) {

        SingleResponse<BOList> listByWorkflowNameOrModuleCodeOrOriginator = getListByWorkflowNameOrModuleCodeOrOriginator(appCode, todoType, instanceName, instanceState, participant, originatorList, loginId, startTime, endTime, pageNum, pageSize, bizObjectId, workflowCode);
//        List<TodoBO> todoBOS = ModelUtil.toModel(listByWorkflowNameOrModuleCodeOrOriginator.getResult(), TodoBO.class);
//        return MultiResponse.ofLong(todoBOS, listByWorkflowNameOrModuleCodeOrOriginator.getTotal());
        return listByWorkflowNameOrModuleCodeOrOriginator;
    }

    public SingleResponse<BOList> getListByWorkflowNameOrModuleCodeOrOriginator(String appCode, Integer todoType, String instanceName, String instanceState, String participant,
                                                                                List<String> originatorList, String loginId,
                                                                                Date startTime, Date endTime, int pageNum, int pageSize, String bizObjectId, String workflowCode) {
        //改为关联查询
        SingleResponse<BOList> objectPageInfo = null;
        PageHelper.startPage(pageNum, pageSize);
        switch (todoType.intValue()) {
            case 1:
                log.info("查询待办");
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, loginId, startTime, endTime, "app_commonservice.biz_todoitem_todo", bizObjectId, workflowCode);
                break;
            case 2:
                log.info("查询待阅");
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, loginId, startTime, endTime, "app_commonservice.biz_todoitem_toberead", bizObjectId, workflowCode);
                break;
            case 3:
                log.info("查询已办");
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, loginId, startTime, endTime, "app_commonservice.biz_todoitem_done", bizObjectId, workflowCode);
                break;
            case 4:
                log.info("查询已阅");
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, loginId, startTime, endTime, "app_commonservice.biz_todoitem_read", bizObjectId, workflowCode);
//                objectPageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
//                    readMapper.selectByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState,participant,moduleCode, originator, loginId, startTime, endTime);
//                });
                break;
            case 0:
                log.info("查询所有");
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectAllByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, startTime, endTime, bizObjectId, workflowCode);
                break;
            case 5:
                log.info("查询我的申请");
                originatorList = Arrays.asList(loginId);
                log.info("####申请人originatorList::{}", JSON.toJSONString(originatorList));
                objectPageInfo = selectAllByWorkflowNameOrModuleCodeOrOriginator(appCode, instanceName, instanceState, originatorList, startTime, endTime, bizObjectId, workflowCode);
                break;
            default:
                break;
        }
        if (objectPageInfo != null) {
            log.info("查询任务总数 = {}.", objectPageInfo.getData().getTotal());
        } else {
            log.info("无任务数据");
        }
        return objectPageInfo;
    }

    public SingleResponse<BOList> selectAllByWorkflowNameOrModuleCodeOrOriginator(String appCode,
                                                                                  String instanceName,
                                                                                  String instanceState,
                                                                                  List<String> originatorList,
                                                                                  Date startTime,
                                                                                  Date endTime, String bizObjectId, String workflowCode) {
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder("SELECT count(*)\n" +
                "        from app_commonservice.biz_workflow_instance wfi left join app_commonservice.biz_todoitem_todo td on td.instance_id = wfi.id\n" +
                "        left join app_commonservice.biz_todoitem_done tdo on tdo.instance_id = wfi.id where 1 = 1");
        StringBuffer sql = new StringBuffer("SELECT IFNULL(td.page_json,tdo.page_json) as page_json,td.*,tdo.*,wfi.state as instanceState,wfi.biz_object_id as bizObjectId, wfi.start_time \n" +
                "        from app_commonservice.biz_workflow_instance wfi left join app_commonservice.biz_todoitem_todo td on td.instance_id = wfi.id\n" +
                "        left join app_commonservice.biz_todoitem_done tdo on tdo.instance_id = wfi.id where 1 = 1");
        Map<String, Object> parameter = new HashMap<>();
//        if (StringUtils.isNotBlank(loginId)) {
//            whereSql.append(" and (td.participant = (:loginId) or td.trustor = (:loginId))");
//            parameter.put("loginId",loginId);
//        }
        if (StringUtils.isNotBlank(instanceName)) {
            whereSql.append(" and wfi.instance_name LIKE  (:instanceName)");
            parameter.put("instanceName", "%" + instanceName + "%");
        }
        if (StringUtils.isNotBlank(workflowCode)) {
            whereSql.append(" and wfi.workflow_code =  (:workflowCode)");
            parameter.put("workflowCode", workflowCode);
        }
        if (StringUtils.isNotBlank(appCode)) {
            whereSql.append(" and wfi.appCode =  (:appCode)");
            parameter.put("appCode", appCode);
        }
        if (!CollectionUtils.isEmpty(originatorList)) {
            whereSql.append(" and wfi.originator in(:originatorList)");
            parameter.put("originatorList", originatorList);
        }
        if (startTime != null) {
            whereSql.append(" and wfi.finish_time &gt;=  (:startTime)");
            parameter.put("startTime", startTime);
        }
        if (endTime != null) {
            whereSql.append(" and wfi.finish_time  &lt;=  (:endTime)");
            parameter.put("endTime", endTime);
        }
        if (StringUtils.isNotBlank(instanceState)) {
            whereSql.append(" and wfi.state =  (:instanceState)");
            parameter.put("instanceState", instanceState);
        }
        if (StringUtils.isNotBlank(bizObjectId)) {
            whereSql.append(" and wfi.biz_object_id =  (:bizObjectId)");
            parameter.put("bizObjectId", bizObjectId);
        }
        countSql.append(whereSql);
        sql.append(whereSql);
        countSql.append("group by wfi.id");
        sql.append(" group by wfi.id order  by wfi.start_time desc");
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
            log.info("流程数量count::{}", count);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList = getObjectDatas(resultList);
        }
        //构建结果集
        log.info("####resultList::{}", JSON.toJSONString(resultList));
        BoResultFormat.resultFormat(resultList, ModelConst.T_FLOW_MANAGE);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_FLOW_MANAGE);
        return SingleResponse.of(bOList);
    }

    /**
     * 流程管理列表
     *
     * @param workflow 流程列表查询参数
     * @return 响应结果
     */
    @Path("searchFlowDetails")
    @POST
    @Operation(summary = "获取流程详情", tags = CUSTOM_SERVICE)
    public Map<String, List<Map<String, Object>>> searchFlowDetails(@Parameter FlowQueryDto workflow) {
        StringBuilder objectSql = new StringBuilder("");
        Map<String, List<Map<String, Object>>> calibrationMap=new HashMap<>();
        Map<String, Object> parameterIds = new HashMap<>();
        parameterIds.put("ids", workflow.getBizObjectIdList());
        //定标流程
        log.info("流程实例workflow_code::{}", workflow.getWorkflowCode());
        if (StringUtils.equals(workflow.getWorkflowCode(), WorkFlowCodeEnum.CALIBRATION.text)) {
            objectSql.append("select ctgp.id,ctgp.createdBy,sqg.* from commoditymaterials.i_commoditymaterials_t_goods_purchase ctgp left join sourcingcenter.i_sourcingcenter_t_inquiry ssi on ssi.id=ctgp.inquiry_id\n" +
                    "left join sourcingcenter.i_sourcingcenter_t_inquiry_goods sig on sig.inquiry_id=ssi.id \n" +
                    "left join sourcingcenter.i_sourcingcenter_t_quotation_goods sqg on sqg.inquiry_goods_id=sig.id");
            objectSql.append(" where 1=1 and ctgp.id in(:ids)");
            List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
            calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
        }
        //订单流程
        if (StringUtils.equals(workflow.getWorkflowCode(), WorkFlowCodeEnum.ORDER.text)) {
            objectSql.append("select * from ordercenter.i_ordercenter_t_order_customer");
            objectSql.append(" where 1=1 and id in(:ids)");
            List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
            calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
        }
        //开票流程
        if (StringUtils.equals(workflow.getWorkflowCode(), WorkFlowCodeEnum.INVOICE.text)) {
            objectSql.append("select * from financialcenter.i_financialcenter_t_invoice_apply");
            objectSql.append(" where 1=1 and id in(:ids)");
            List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
            calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
        }
        //付款流程
        if (StringUtils.equals(workflow.getWorkflowCode(), WorkFlowCodeEnum.PURCHASEPAYMENT.text)) {
            objectSql.append("select * from financialcenter.i_financialcenter_t_settle");
            objectSql.append(" where 1=1 and id in(:ids)");
            List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
            calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
        }

        return calibrationMap;
    }

    public List<Map<String, Object>> getObjectDatas(List<Map<String, Object>> resultList) {
        Map<String, List<Map<String, Object>>> workflowCodeMap = resultList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("workflow_code"))));
        for (Map.Entry<String, List<Map<String, Object>>> workflow : workflowCodeMap.entrySet()) {
            StringBuilder objectSql = new StringBuilder("select * from ");
            List<String> ids = workflow.getValue().stream().map(e -> e.get("bizObjectId").toString()).collect(Collectors.toList());
            Map<String, Object> parameterIds = new HashMap<>();
            parameterIds.put("ids", ids);
            //定标流程
            log.info("流程实例workflow_code::{}", workflow.getKey());
            if (StringUtils.equals(workflow.getKey(), WorkFlowCodeEnum.CALIBRATION.text)) {
                String objectTableName = "commoditymaterials.i_commoditymaterials_t_goods_purchase";
                objectSql.append(objectTableName);
                objectSql.append(" where 1=1 and id in(:ids)");
                List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
                Map<String, List<Map<String, Object>>> calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
                for (Map<String, Object> resultMap : resultList) {
                    if (!CollectionUtils.isEmpty(calibrationMap.get(resultMap.get("bizObjectId").toString()))) {
                        Map<String, Object> map = calibrationMap.get(resultMap.get("bizObjectId").toString()).get(0);
                        resultMap.put("name", map.get("name"));
                        resultMap.put("num", map.get("num"));
                        resultMap.put("unit", map.get("unit"));
                        resultMap.put("pretax_price", map.get("pretax_price"));
                        resultMap.put("pretax_amount", map.get("pretax_amount"));
                    }
                }
            }
//
//            if (StringUtils.equals(workflow.getKey(), WorkFlowCodeEnum.ORDER.text)) {
//                String objectTableName = "ordercenter.i_ordercenter_t_order_customer";
//                objectSql.append(objectTableName);
//                objectSql.append(" where 1=1 and id in(:ids)");
//                List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
//                Map<String, List<Map<String, Object>>> calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
//                for (Map<String, Object> resultMap : resultList) {
//                    if (!CollectionUtils.isEmpty(calibrationMap.get(resultMap.get("bizObjectId").toString()))) {
//                        Map<String, Object> map = calibrationMap.get(resultMap.get("bizObjectId").toString()).get(0);
//                        resultMap.put("name", map.get("name"));
//                        resultMap.put("num", map.get("num"));
//                        resultMap.put("unit", map.get("unit"));
//                        resultMap.put("pretax_price", map.get("pretax_price"));
//                        resultMap.put("pretax_amount", map.get("pretax_amount"));
//                    }
//                }
//            }
//
//            if (StringUtils.equals(workflow.getKey(), WorkFlowCodeEnum.INVOICE.text)) {
//                String objectTableName = "financialcenter.i_financialcenter_t_invoice_apply";
//                objectSql.append(objectTableName);
//                objectSql.append(" where 1=1 and id in(:ids)");
//                List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
//                Map<String, List<Map<String, Object>>> calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
//                for (Map<String, Object> resultMap : resultList) {
//                    if (!CollectionUtils.isEmpty(calibrationMap.get(resultMap.get("bizObjectId").toString()))) {
//                        Map<String, Object> map = calibrationMap.get(resultMap.get("bizObjectId").toString()).get(0);
//                        resultMap.put("name", map.get("name"));
//                        resultMap.put("num", map.get("num"));
//                        resultMap.put("unit", map.get("unit"));
//                        resultMap.put("pretax_price", map.get("pretax_price"));
//                        resultMap.put("pretax_amount", map.get("pretax_amount"));
//                    }
//                }
//            }
//
//            if (StringUtils.equals(workflow.getKey(), WorkFlowCodeEnum.PURCHASEPAYMENT.text)) {
//                String objectTableName = "financialcenter.i_financialcenter_t_settle";
//                objectSql.append(objectTableName);
//                objectSql.append(" where 1=1 and id in(:ids)");
//                List<Map<String, Object>> calibrationList = jdbcTemplate.queryForList(objectSql.toString(), parameterIds);
//                Map<String, List<Map<String, Object>>> calibrationMap = calibrationList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("id"))));
//                for (Map<String, Object> resultMap : resultList) {
//                    if (!CollectionUtils.isEmpty(calibrationMap.get(resultMap.get("bizObjectId").toString()))) {
//                        Map<String, Object> map = calibrationMap.get(resultMap.get("bizObjectId").toString()).get(0);
//                        resultMap.put("name", map.get("name"));
//                        resultMap.put("num", map.get("num"));
//                        resultMap.put("unit", map.get("unit"));
//                        resultMap.put("pretax_price", map.get("pretax_price"));
//                        resultMap.put("pretax_amount", map.get("pretax_amount"));
//                    }
//                }
//            }
        }
        return resultList;
    }

    public SingleResponse<BOList> selectByWorkflowNameOrModuleCodeOrOriginator(String appCode,
                                                                               String instanceName,
                                                                               String instanceState,
                                                                               List<String> originatorList,
                                                                               String loginId,
                                                                               Date startTime,
                                                                               Date endTime, String tableName, String bizObjectId, String workflowCode) {
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder("SELECT count(*) \n" +
                "         from " + tableName + " td left join app_commonservice.biz_workflow_instance wfi on td.instance_id = wfi.id \n" +
                "         where 1 = 1");
        StringBuffer sql = new StringBuffer("SELECT td.*,wfi.state as instanceState,wfi.biz_object_id as bizObjectId, wfi.start_time \n" +
                "        from " + tableName + " td left join app_commonservice.biz_workflow_instance wfi on td.instance_id = wfi.id\n" +
                "        where 1 = 1");
        Map<String, Object> parameter = new HashMap<>();
        if (StringUtils.isNotBlank(loginId)) {
            whereSql.append(" and (td.participant = (:loginId) or td.trustor = (:loginId))");
            parameter.put("loginId", loginId);
        }
        if (StringUtils.isNotBlank(instanceName)) {
            whereSql.append(" and td.instance_name LIKE  (:instanceName)");
            parameter.put("instanceName", "%" + instanceName + "%");
        }
        if (StringUtils.isNotBlank(workflowCode)) {
            whereSql.append(" and td.workflow_code =  (:workflowCode)");
            parameter.put("workflowCode", workflowCode);
        }
        if (StringUtils.isNotBlank(appCode)) {
            whereSql.append(" and td.appCode =  (:appCode)");
            parameter.put("appCode", appCode);
        }
        if (!CollectionUtils.isEmpty(originatorList)) {
            whereSql.append(" and td.originator in(:originatorList)");
            parameter.put("originatorList", originatorList);
        }
        if (startTime != null) {
            whereSql.append(" and wfi.finish_time >=  (:startTime)");
            parameter.put("startTime", startTime);
        }
        if (endTime != null) {
            whereSql.append(" and wfi.finish_time  <=  (:endTime)");
            parameter.put("endTime", endTime);
        }
        if (StringUtils.isNotBlank(instanceState)) {
            whereSql.append(" and wfi.state =  (:instanceState)");
            parameter.put("instanceState", instanceState);
        }
        if (StringUtils.isNotBlank(bizObjectId)) {
            whereSql.append(" and wfi.biz_object_id =  (:bizObjectId)");
            parameter.put("bizObjectId", bizObjectId);
        }
        countSql.append(whereSql);
        sql.append(whereSql);
        if ("biz_todoitem_todo".equals(tableName)) {
            sql.append(" order  by wfi.start_time desc");
        }
        if ("biz_todoitem_toberead".equals(tableName)) {
            sql.append(" order by td.remind_time desc,td.start_time desc");
        }
        if ("biz_todoitem_done".equals(tableName)) {
            sql.append(" order  by td.finish_time desc");
        }
        if ("biz_todoitem_read".equals(tableName)) {
            sql.append(" order  by td.finish_time desc");
        }
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
            log.info("流程数量count::{}", count);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }

        if (!CollectionUtils.isEmpty(resultList)) {
            resultList = getObjectDatas(resultList);
        }
        //构建结果集
        log.info("####resultList::{}", JSON.toJSONString(resultList));
        BoResultFormat.resultFormat(resultList, ModelConst.T_FLOW_MANAGE);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_FLOW_MANAGE);
        return SingleResponse.of(bOList);
    }

    /**
     * 批量提交
     *
     * @param batchSubmitDto 批量提交参数参数
     * @return 响应结果
     */
    @Path("batchSubmitApproval")
    @POST
    @Operation(summary = "批量提交流程", tags = CUSTOM_SERVICE)
    public SingleResponse<HandleWorkItemValidMessageVO> batchSubmitApproval(@Parameter BatchSubmitDto batchSubmitDto) {
        List<Map<String, Object>> approvalList = batchSubmitDto.getApprovalList();
        if (CollectionUtils.isEmpty(batchSubmitDto.getApprovalList())) {
            throw new RuntimeException("请选择流程实例!");
//            return SingleResponse.error("","请选择流程实例!");
        }
        Map<String, List<Map<String, Object>>> approvalMap = approvalList.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("workflow_code"))));
        if (approvalMap.size() > 1) {
            throw new RuntimeException("批量提交的流程类型需一致!");
//            return SingleResponse.error("","批量提交的流程类型需一致!");
        }

        String appCode = approvalList.get(0).get("app_code").toString();
        log.info("调用应用appCode::{}", appCode);
        String url = HttpClients.getUrl(appCode, ServiceUrlConst.APPROVAL_BATCH_SUBMIT_URL);
        Map<String, Object> fileParam = Maps.newHashMap();
        fileParam.put("userId", RequestContext.getCorpLoginId());
        fileParam.put("appCode", appCode);
        fileParam.put("workItemIds", batchSubmitDto.getWorkItemIds());
        fileParam.put("content", batchSubmitDto.getContent());
        String execute = HttpClients.execute(url, fileParam);
        log.info("返回结果::{}", JSON.toJSONString(execute));
        log.info("返回结果success::{}", JSONObject.parseObject(execute).get("success").toString());
        SingleResponse result = JSONObject.parseObject(JSONObject.parseObject(execute).toString(), SingleResponse.class);
        ;
//        if ("true".equals(JSONObject.parseObject(execute).get("success").toString())){
//            result = JSONObject.parseObject(JSONObject.parseObject(execute).get("data").toString(), SingleResponse.class);
//        }else {
//            throw new RuntimeException("批量提交流程出错！！");
////            return SingleResponse.error("","批量提交流程出错！！");
//        }
        return result;
    }
}
